package com.huang.eduorder.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huang.eduorder.client.EduClient;
import com.huang.eduorder.client.OrderClient;
import com.huang.eduorder.component.CourseContant;
import com.huang.eduorder.entity.Order;
import com.huang.eduorder.entity.SkillCourse;
import com.huang.eduorder.mapper.OrderMapper;
import com.huang.eduorder.service.OrderService;
import com.hunag.utils.orderVo.CourseWebVoOrder;
import com.hunag.utils.orderVo.EduCourseOrder;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-04-03
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {


    @Autowired
    private EduClient eduClient;
    @Autowired
    private OrderClient orderClient;

    @Autowired
    CuratorFramework curatorFramework;


    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    // 普通下单
    @Override
    public String createOrder(String courseId, String id) {
        //远程调用获取用户信息
        CourseWebVoOrder courseInfoOrder = eduClient.getCourseInfoOrder(courseId);
        Order order = new Order();
        order.setCourseId(courseId);
        order.setCover(courseInfoOrder.getCover());
        order.setTitle(courseInfoOrder.getTitle());
        order.setTotalFee(courseInfoOrder.getPrice());
        order.setTeacherName(courseInfoOrder.getTeacherName());
        order.setMemberId(id);
        order.setStatus(0);
        baseMapper.insert(order);
        return order.getId();
    }


    // mq异步处理订单
    @Override
    public Order createOrder2(String memberId, SkillCourse courseVo) throws Exception {
        Order order = new Order();
        //查看库存 是否过期 是否有库存
        String key=CourseContant.PRODUCT_KILL+courseVo.getCourseId();

        InterProcessMutex interProcessMutex = new InterProcessMutex(curatorFramework,  "/"+key);
        interProcessMutex.acquire();
        SkillCourse courseOrder = (SkillCourse) redisTemplate.opsForValue().get(key);
        if (courseOrder.getCount() > 0) {//该商品还在秒杀
            //预减库存
            try {
                courseOrder.setCount(courseOrder.getCount() - 1);
                System.out.println(courseOrder.getCount() - 1 + "-s");
                redisTemplate.opsForValue().set(key,courseOrder,
                        redisTemplate.opsForValue().getOperations().getExpire(key), TimeUnit.SECONDS);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //  释放锁
                interProcessMutex.release();
            }
        } else {
            // 商品秒杀已下架   抛出异常
            return order;
        }

            //创建订单信息I
//        CourseWebVoOrder courseInfoOrder = eduClient.getCourseInfoOrder(courseOrder.getCourseId());
            order.setId(UUID.randomUUID().toString().replace("-",""));
            order.setMemberId(memberId);
            order.setCourseId(courseOrder.getCourseId());
            order.setStatus(0); //还未支付
            order.setCover(courseVo.getCover());
            order.setTotalFee(courseVo.getPrice());

//             order.setTitle(courseInfoOrder.getTitle());
//             order.setTeacherName(courseInfoOrder.getTeacherName());

            //mq发送
            MessageProperties messageProperties = new MessageProperties();
            messageProperties.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN);

            Message msg = MessageBuilder.withBody(new ObjectMapper().writeValueAsBytes(order)).setDeliveryMode(MessageDeliveryMode.PERSISTENT).build();
            try {
                // 发送订单消息
                rabbitTemplate.convertAndSend("orderExchange","normalkey",msg);

            } catch (AmqpException e) {
                // 发送消息发送异常
                System.out.println("消息发送失败   还原库存");
                courseVo.setCount(courseVo.getCount()+1);
                redisTemplate.opsForValue().set(key,courseOrder,
                        redisTemplate.opsForValue().getOperations().getExpire(key));
            }



        return order;
    }

    @Override
    public Boolean isBuy(String courseId, String memberId) {
         QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        wrapper.eq("member_id",memberId);
        wrapper.eq("status","1");
         List<Order> orders = baseMapper.selectList(wrapper);
         if(orders.size()>0){
             return true;
         }else{
             return false;
         }

    }

    @Override
    public void updateStatus(String orderId) {
            baseMapper.updateStatus(orderId);
    }

    @Override
    public List<EduCourseOrder> getBuyList(String memberId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("member_id",memberId);
        List<Order> orders = baseMapper.selectList(wrapper);
        ArrayList<String> strings = new ArrayList<>();
        for (Order order : orders) {
            strings.add(order.getCourseId());
        }
        return   eduClient.getBuyCourseList(strings);

    }


}
